/*
 *  Core.cpp
 *  allInOne
 *
 *  Created by James Johns on 01/11/2009.
 *  Copyright 2009 xD-Duncesoft. All rights reserved.
 *
 */

#include "Core.h"
#include "standardTemplate.h"
#include <iostream>


Core::Core() {
	terminal = new commandLine;
	numberOfCommands = 0;
}
Core::~Core() {
	delete terminal;
	while (numberOfCommands != 0) {
		delete commands[numberOfCommands];
		numberOfCommands--;
	}
}

void Core::registerCommand(const char *command, commandReference *plugin) {
	commands[numberOfCommands] = new char [strlen(command)];
	
	comRefs[numberOfCommands].pluginClass = plugin->pluginClass;
	comRefs[numberOfCommands].functionNumber = plugin->functionNumber;
	
	
	numberOfCommands++;
}

void Core::receivedCommand(char *command) {
	int i=0;
	while (command[i] != 0x20 && command[i] != 0x00) {
		i++;
	}
	int j = 0;
	while (command[j] != 0x00) {
		j++;
	}
	
	char *commandWord = new char [i+1];
	char *parameters = new char [j-i];
	
	int k = j - (i+1);
	while (j >= k) {
		parameters[j-i] = command[j];
		j--;
	}
	
	commandWord[i+1] = 0x00;
	
	i = i-1;
	while (i >= 1) {
		commandWord[i] = command[i];
		i--;
	}
	
	i = 0;
	while (command != commands[i] && i < MAX_COM_REF) {
		i++;
	}
	
	if(i == MAX_COM_REF){
		terminal->print("invalid command!\n");
	}
	else{
		int fNum = comRefs[i].functionNumber;
		comRefs[i].pluginClass->run(fNum, parameters);
		terminal->print(strcat(command,"\n"));
	}
	
}

void Core::requestCommand(const char *command) {
	char inputBuffer[256];
	char *newCommand;
	newCommand = new char [strlen(command)+2];
	newCommand = strcpy(newCommand, command);
	newCommand = strcat(newCommand, "> ");
	
	terminal->requestCommand(newCommand, inputBuffer);
	receivedCommand(inputBuffer);
	delete newCommand;
}
